package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String BasePath;

    @PostMapping("upload")
    public R<String> upload(MultipartFile file) throws IOException {

        File filePath = new File(BasePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        String fileName = UUID.randomUUID() + suffix;

        System.out.println(fileName+"566666");

        file.transferTo(new File(BasePath + fileName));
        return R.success(fileName);

    }


    @GetMapping("download")
    public void download(HttpServletResponse response, String name) throws IOException {
        InputStream inputStream = new FileInputStream(new File(BasePath+name));
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream,outputStream);

    }
}
